// HTTP请求发送和响应处理功能
function initHttpFunctions(app) {
    // 扩展HttpRequestTool类，添加HTTP请求相关方法
    Object.assign(app, {
        async sendRequest() {
            // 判断当前选中的 option-tab
            const activeOptionTab = document.querySelector('.option-tab.active');
            if (activeOptionTab && activeOptionTab.dataset.option === 'advanced') {
                // 如果当前是高级选项，则切换到请求头
                this.switchOptionTab('headers');
            }
            const sendBtn = document.getElementById('send-btn');
            sendBtn.disabled = true;
            sendBtn.textContent = '发送中...';

            try {
                // 保存当前标签页数据
                this.saveCurrentTabData();

                const tab = this.tabs.get(this.currentTab);
                
                // 应用全局请求头（全局请求头优先级低于标签页请求头）
                let headers = tab.headers || {};
                if (this.applyGlobalHeaders) {
                    headers = this.applyGlobalHeaders(headers);
                }
                
                const requestData = {
                    method: tab.method,
                    url: tab.url,
                    headers: headers,
                    body: tab.body,
                    options: this.getCurrentOptions() // 动态获取最新 options
                };

                const response = await sendRequest(requestData);
                
                // 将响应结果保存到当前标签页
                const currentTab = this.tabs.get(this.currentTab);
                if (currentTab) {
                    currentTab.response = response;
                    this.tabs.set(this.currentTab, currentTab);
                }
                
                this.displayResponse(response);

                // 发送成功后保存到历史记录，包含处理后的URL
                await this.saveToHistory(requestData, response.processedUrl);

            } catch (error) {
                // 错误情况下也要保存错误信息到标签页
                const currentTab = this.tabs.get(this.currentTab);
                if (currentTab) {
                    currentTab.response = { error: error.message };
                    this.tabs.set(this.currentTab, currentTab);
                }
                
                this.displayError(error.message);
            } finally {
                sendBtn.disabled = false;
                sendBtn.textContent = '发送';
            }
        },

        displayResponse(response) {
            // 显示状态
            const statusBadge = document.getElementById('response-status');
            if (response.error) {
                statusBadge.textContent = '错误';
                statusBadge.className = 'status-badge error';
                document.getElementById('response-time').textContent = '0ms';
                document.getElementById('response-body-content').textContent = response.error;
            } else {
                statusBadge.textContent = response.status;
                statusBadge.className = `status-badge ${response.status >= 200 && response.status < 300 ? 'success' : 'error'}`;
                document.getElementById('response-time').textContent = `${response.duration}ms`;
                document.getElementById('response-body-content').textContent = this.formatJson(response.body);
            }
            // 显示响应头
            const headers = response.headers || {};
            const headersText = Object.entries(headers)
                .map(([key, value]) => `${key}: ${value}`)
                .join('\n');
            document.getElementById('response-headers-content').textContent = headersText;
        },

        displayError(error) {
            document.getElementById('response-status').textContent = 'ERROR';
            document.getElementById('response-status').className = 'status-badge error';
            document.getElementById('response-time').textContent = '';
            document.getElementById('response-body-content').textContent = error;
            document.getElementById('response-headers-content').textContent = '';
        },

        formatJson(text) {
            try {
                const obj = JSON.parse(text);
                return JSON.stringify(obj, null, 2);
            } catch {
                return text;
            }
        },

        clearResponseArea() {
            // 清空响应状态
            const statusBadge = document.getElementById('response-status');
            if (statusBadge) {
                statusBadge.textContent = '';
                statusBadge.className = 'status-badge';
            }

            // 清空响应时间
            const responseTime = document.getElementById('response-time');
            if (responseTime) {
                responseTime.textContent = '';
            }

            // 清空响应内容
            const responseContent = document.getElementById('response-body-content');
            if (responseContent) {
                responseContent.textContent = '';
            }

            // 清空响应头
            const responseHeaders = document.getElementById('response-headers-content');
            if (responseHeaders) {
                responseHeaders.textContent = '';
            }
        }
    });
}

// 全局函数定义
async function sendRequest(requestData) {
    try {
        const response = await fetch('/api/request', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(requestData)
        });

        if (response.ok) {
            return await response.json();
        } else {
            throw new Error(`请求失败: ${response.status} ${response.statusText}`);
        }
    } catch (error) {
        throw new Error(`网络错误: ${error.message}`);
    }
}

// 导出函数以便在其他文件中使用
window.initHttpFunctions = initHttpFunctions;